package com.newly.gateway.utils;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.newly.common.base.entity.R;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

public class ResponseUtil {

    public static Mono<Void> write(ServerWebExchange exchange, HttpStatus httpStatus, R<Object> r) {
        // 说明token无效，抛出401状态码
        ServerHttpResponse response = exchange.getResponse();
        response.getHeaders().add("content-type",
                "application/json;charset=utf-8");
        response.setStatusCode(httpStatus);
        ObjectMapper objectMapper = new ObjectMapper();
        byte[] flush = new byte[1024];
        try {
            flush = objectMapper.writeValueAsBytes(r);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        DataBuffer wrap = response.bufferFactory().wrap(flush);
        return response.writeWith(Mono.just(wrap));
    }
}
